<template>
  <el-dialog
    :title="title"
    :visible.sync="addVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @click="handleCancel"
  >
    <el-form :model="userInfo">
      <el-form-item label="用户id" :label-width="formLabelWidth" v-if="!isAdd">
        <el-input v-model="userInfo.id" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户名" :label-width="formLabelWidth">
        <el-input v-model="userInfo.username"></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" :label-width="formLabelWidth">
        <el-input v-model="userInfo.realName"></el-input>
      </el-form-item>
      <el-form-item label="昵称" :label-width="formLabelWidth">
        <el-input v-model="userInfo.nickName"></el-input>
      </el-form-item>
      <el-form-item label="密码" :label-width="formLabelWidth">
        <el-input v-model="userInfo.password"></el-input>
      </el-form-item>
      <el-form-item label="性别" :label-width="formLabelWidth">
        <el-switch
          style="display: block"
          v-model="userInfo.gender"
          :active-value="1"
          :inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
          active-text="男"
          inactive-text="女"
        >
        </el-switch>
        <!-- <el-input v-model="userInfo.gender"></el-input> -->
      </el-form-item>
      <el-form-item label="电话" :label-width="formLabelWidth">
        <el-input v-model="userInfo.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" :label-width="formLabelWidth">
        <el-input v-model="userInfo.email"></el-input>
      </el-form-item>
      <!-- 上传头像 -->
      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          action="/api/auth/user/upload"
          :show-file-list="false"
          name="face"
          :headers="headers"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { UserInfoByIdApi, addUserApi, editUserApi } from "@/Api/UserApi";
export default {
  props: ["addVisible", "title"],
  data() {
    return {
      userInfo: {
        id: 0,
        username: "",
        password: "",
        realName: "",
        nickName: "",
        gender: 1,
        phone: "",
        email: "",
        avatar: "",
      },
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      isAdd: true,
      formLabelWidth: "120px",
    };
  },
  methods: {
    handleCancel() {
      this.$emit("closeAddDialog");
    },
    async handleSave() {
      try {
        let res;
        if (this.isAdd) {
          res = await addUserApi(this.userInfo);
        } else {
          res = await editUserApi(this.userInfo);
        }

        if (res.status == 200) {
          this.$message({
            message: res.msg,
            type: "success",
            duration: 200,
            onClose: () => {
              this.$emit("closeAddDialog", true);
            },
          });
        } else {
          this.$message({
            message: res.msg,
            type: "error",
            duration: 1000,
          });
        }
      } catch (error) {
        this.loading = false;
        this.$message({
          message: "系统异常",
          type: "error",
          duration: 1000,
        });
      }
    },
    async openDialog(userId) {
      if (!userId) {
        this.resetForm();
        this.isAdd = true;
      } else {
        this.isAdd = false;
        try {
          this.loading = true;
          const res = await UserInfoByIdApi(userId);
          if (res.status == 200) {
            this.userInfo = res.data;
            this.loading = false;
          } else {
            this.loading = false;
            this.$message({
              message: res.msg,
              type: "error",
              duration: 1000,
            });
          }
        } catch (error) {
          this.loading = false;
          this.$message({
            message: "系统异常",
            type: "error",
            duration: 1000,
          });
        }
      }
    },
    //上传校验之前
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //上传成功
    handleAvatarSuccess(res, file) {
      if (!res || !res.data) {
        this.$message.error("上传返回数据异常");
        return;
      }
      // console.log(res);
      // console.log(file.raw);

      if (res.status == 200) {
        const fileName = res.data.fileName;
        const hostName = res.data.hostName;
        this.userInfo.avatar = hostName + fileName;
        console.log(this.userInfo.avatar);
        // console.log("成功");
      } else {
        this.$message.error(res.msg);
      }

      //   this.imageUrl = URL.createObjectURL(file.raw);
    },
    resetForm() {
      this.userInfo = {
        id: 0,
        username: "",
        password: "",
        realName: "",
        nickName: "",
        gender: 0,
        phone: "",
        email: "",
        avatar: "",
      };
    },
  },
};
</script>

<style lang="less" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>    